/*
 * @(#)IKTokenizer.java, 2024/1/10 11:38
 *
 * Copyright (c) 2018-2024, 四川蜀天梦图数据科技有限公司.
 * All rights reserved.
 */
package com.zhoufan.lucene.ik;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.AttributeFactory;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;

/**
 * IKTokenizer
 *
 * @author fantazy
 * @version 1.0, 2024年01月10日
 */
public final class IKTokenizer extends Tokenizer
{

    // IK分词器实现
    private IKSegmenter _IKImplement;

    private final CharTermAttribute termAttr;

    private final OffsetAttribute offsetAttr;

    private final TypeAttribute typeAttr;

    private int endPosition;

    public IKTokenizer(AttributeFactory factory,boolean useSmart)
    {
        super(factory);
        this.termAttr = addAttribute(CharTermAttribute.class);
        this.offsetAttr = addAttribute(OffsetAttribute.class);
        this.typeAttr = addAttribute(TypeAttribute.class);
        _IKImplement = new IKSegmenter(input, useSmart);
    }

    @Override
    public boolean incrementToken() throws IOException
    {
        // 清除所有的词元属性
        clearAttributes();
        Lexeme nextLexeme = _IKImplement.next();
        if (nextLexeme != null) {
            // 将Lexeme转成Attributes
            // 设置词元文本
            termAttr.append(nextLexeme.getLexemeText());
            // 设置词元长度
            termAttr.setLength(nextLexeme.getLength());
            // 设置词元位移
            offsetAttr.setOffset(nextLexeme.getBeginPosition(), nextLexeme.getEndPosition());
            // 记录分词的最后位置
            endPosition = nextLexeme.getEndPosition();
            // 记录词元分类
            typeAttr.setType(nextLexeme.getLexemeTypeString());
            // 返会true告知还有下个词元
            return true;
        }
        // 返会false告知词元输出完毕
        return false;
    }
}
